package datos.conexion;

import java.io.IOException;
import java.sql.*;

import logica.ajustes.ValorPorDefecto;
import logica.ajustes.ValorPorDefectoBDH2;

/**
 * 
 * @author dullC
 */
public class ConexionH2 {
	public final String CLASE_CONEXION = "org.h2.Driver";
	private String user;
	private String password;
	private String url;
	private Connection conn;
	private Statement stm;
	private ValorPorDefectoBDH2 vpd;

	public ConexionH2() throws IOException, InstantiationException,
			IllegalAccessException, ClassNotFoundException, SQLException {

		cargarParametrosConexion();
		url = vpd.getUrl() + ";SCHEMA=" + vpd.getSchema();
		user = vpd.getUser();
		password = vpd.getPassword();
		conectar();
	}

	public void cargarScriptSql() {
		executeUpdateStatement("RUNSCRIPT FROM '" + vpd.getScriptSql() + "'");
	}

	private ValorPorDefecto cargarParametrosConexion() {
		vpd = new ValorPorDefectoBDH2();
		vpd.cargarArchivo(ValorPorDefectoBDH2.archivoAjustes);
		return vpd;
	}

	public static void pruebaConexion(String schema, String url, String user,
			String password) throws InstantiationException,
			IllegalAccessException, ClassNotFoundException, SQLException {

		Class.forName("org.h2.Driver").newInstance();
		Connection conn = DriverManager.getConnection(
				url + ";SCHEMA=" + schema, user, password);
		conn.close();
	}

	private void conectar() throws InstantiationException,
			IllegalAccessException, ClassNotFoundException, SQLException {

		Class.forName(CLASE_CONEXION).newInstance();
		conn = DriverManager.getConnection(url, user, password);
		System.out.println("Conectado a H2");
	}

	public boolean executeUpdateStatement(String cad) {
		try {
			stm = conn.createStatement();
			stm.executeUpdate(cad);
			stm.close();
			// System.out.println("Actualizacion realizada... ");
		} catch (SQLException e) {
			// System.out.println("No se pudo realizar la actualizacion... " +
			// e);
		}
		return true;
	}

	public ResultSet executeQueryStatement(String cad) {
		ResultSet res = null;
		try {
			stm = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
					ResultSet.CONCUR_UPDATABLE);
			res = stm.executeQuery(cad);
			// System.out.println("Consulta realizada...");
		} catch (SQLException e) {
			System.out.println("No se pudo realizar la consulta... " + e);
		}

		return res;
	}

	public void cerrarConexion() throws SQLException {
		conn.close();
		System.out.println("Desconectado");
	}

}
